<?php
namespace  common\components\services\goods;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Brand;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use common\models\datas\Customer;
use common\models\datas\Type;
use common\models\datas\TypeBrand;
use frontend\models\datas\Arrangement;
use frontend\models\datas\ClassManage;
use frontend\models\datas\ClassroomAttr;
use frontend\models\datas\Course;
use frontend\models\datas\Goods;
use frontend\models\datas\GoodsAttr;
use frontend\models\datas\Mechanic;
use frontend\models\datas\Teacher;
use yii\base\Action;
use yii\base\ErrorException;
use yii\base\Exception;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;


class CreateAction extends Action{

    public $default_url='@common/components/services/goods/defaultview.php';

    public $type;

    public function run(){
        if (\Yii::$app->request->get('type_id') == null) {
            throw new BadRequestHttpException(\Yii::t('frontend', '商品类型不存在'));
        }
        $this->type= \Yii::$app->request->get('type_id');
        $model=new Goods();
        $model->scenario = 'create';
        $model->loadDefaultValues();
        $goodattr=new GoodsAttr();
        $tree=$this->getCategory($this->type);
        $brand=$this->getTypeBrand($this->type);
        $mechanic=$this->getMechanic();
        if(count($mechanic) == 1){
            foreach($mechanic as $key=>$v){
                $model->mechanic_id = $key;
            }
        }
        $attribute=Fun::getAttribute($this->type);
        if (\Yii::$app->request->isAjax && $this->type=1) {
             return $this->returnAjaxCourseData();
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post()['Goods'])) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post())&& $model->validate()) {
            if($this->type==1){
                return $this->CourseSave($model,\Yii::$app->request->post());
            }elseif($this->type==2 || $this->type==4){//后期直接改成 !=3就行了，3是舞台表演
                //乐器超市商品
                return $this->ProductSave($model,\Yii::$app->request->post());
            }
        }/*else{
            \Yii::error('更新商品信息失败，验证错误信息：');
            \Yii::error($model->getErrors());
        }*/
        $is_update = false;
        return $this->controller->render('create',['model'=>$model,'tree'=>$tree,'brand'=>$brand,'mechanic'=>$mechanic,'goods_attr'=>$goodattr,'attribute'=>$attribute,'default'=>\Yii::$app->view->render($this->default_url,['model'=>$model,'tree'=>$tree,'brand'=>$brand,'mechanic'=>$mechanic,'goods_attr'=>$goodattr,'attribute'=>$attribute,'type_id'=>$this->type,'is_update'=>$is_update])]);
    }

    public function getCategory($type_id){
        $site_id=Fun::getSiteId();
        $cate_attr=CateAttr::find()->select(['cat_id'])->where(['or',['mobile_is_show'=>1],['pc_is_show'=>1]])->andWhere(['site_id'=>$site_id])->orderBy('pc_sort asc')->column();
        $category=Cate::find()->indexBy('id')->where(['in','id',$cate_attr])->andWhere(['type_id'=>$type_id])->asArray()->all();
        //$category = Cate::find()->indexBy('id')->where(['is_delete'=>0,'type_id'=>$type_id])->asArray()->all();
        $tree = (new Tree($category))->get_tree_select();
        return  $tree;
    }

    public function getTypeBrand($type_id){
        $brand_id=TypeBrand::find()->select(['brand_id'])->where(['type_id'=>$type_id])->column();
        $brand=Brand::find()->where(['in','id',$brand_id])->all();
        $result = ArrayHelper::map($brand, 'id', 'name');
        return  $result;
    }

    public function getMechanic(){
        $mids = Fun::getMechanicIds();
        $mechanicModel=Mechanic::find()->where(['site_id'=>Fun::getSiteId(),'is_delete'=>0,'status'=>1]);
        if($mids){
            $mechanicModel->andWhere(['id'=>$mids]);
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        $tree_mechanic=(new Tree($mechanic))->get_tree_select();
        //$result = ArrayHelper::map($mechanic, 'id', 'name');
        return  $tree_mechanic;
    }

    public function  ReturnAjaxCourseData(){
        if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = Arrangement::find()->where(['is_delete'=>0])->orderBy('id ASC');
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['course_name'])) {
                $id = Course::find()->select('id')->where(['like', 'name', $search_data['course_name']])->column();
                $data->andWhere(['in', 'course_id', $id]);
            }
            if (!empty($search_data['teacher_name'])) {
                $idS = Teacher::find()->select('id')->where(['like', 'name', $search_data['teacher_name']])->column();
                $data->andWhere(['in', 'teacher_id', $idS]);
            }
            if (!empty($search_data['class_day'])) {
                $classroom_attr_id = ClassroomAttr::find()->where(['classday' => $search_data['class_day'], 'status' => 1])->asArray()->column();
                $data->andWhere(['in', 'classroom_attr_id', $classroom_attr_id]);
            }
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array=Fun::asArray($model, ['course_name','teacher_name','room_number','class_day','start_time','end_time','booking']);
        $ajax_object = new AjaxObject();
        $ajax_object->data =$array;
        $ajax_object->pages = $pages;
        return $ajax_object;
    }

    public function CourseSave($model,$post){
        $arrangement=Arrangement::findOne([$model->arrangement_id]);
        if($arrangement===null){
            throw new NotFoundHttpException(\Yii::t('frontend', '排课信息不存在'));
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try{
        $model->name=isset($arrangement->course)?$arrangement->course->name:'';
        $model->sn='course'.time();
        $model->cat_id=isset($arrangement->course)?$arrangement->course->category_id:'';
        $model->type_id=$this->type;
        $model->price=$arrangement->price;
        $model->market_price=$arrangement->market_price;
        $model->store=$arrangement->max_number;
        $model->description=isset($arrangement->teacher) ? $arrangement->teacher->description : '';
        $model->content=isset($arrangement->course) ? $arrangement->course->description : '';
        $model->site_id=Fun::getSiteId();
        $model->mechanic_id=isset($arrangement->teacher) ? $arrangement->teacher->mechanic_id : '';
        $model->goods_type='normal';
        $model->admin_id=\Yii::$app->user->id;
        if($model->is_shelve==1){
            $model->up_at=time();
        }
        if($model->picture != null){//方便后期统计媒体文件，所以在medias表中也保存一下
            $model->imageList = $model->picture;
        }

        if($model->save(false)){
            if($model->is_shelve==1){
                $model->up_at=time();
                $class_manage=new ClassManage();
                $class_manage->class_code='c'.time();
                $class_manage->is_book=$arrangement->is_booking;
                $class_manage->is_old=0;
                $class_manage->associate_id=$model->id;
                $class_manage->mechanic_id=$model->mechanic_id;
                $class_manage->save(false);
            }
            $attribute = isset($post['attribute'])?$post['attribute']:null;
            if(!empty($attribute)){
                if(!empty($post['attr_value'])){
                    foreach($post['attr_value'] as $k=>$v){
                        if(!empty($v)) {
                            $attributes = new GoodsAttr(['goods_id' => $model->id, 'attribute_id' => $k,'name'=>$attribute[$k], 'value' => $v, 'obj_type' => 'attribute']);
                            $attributes->save(false);
                        }
                    }
                }
            }

            $fleds = [
                'class_length' =>[
                    'name' => '上课时长',
                    'obj_type' => 'class_length',
                ],
                'class_count'=>[
                    'name' => '上课次数',
                    'obj_type'  =>'class_count',
                ],
                'max_number'=>[
                    'name' => '最满人数',
                    'obj_type'=>'max_number'
                ],
                'opening_number' =>[
                    'name' => '开课人数',
                    'obj_type' => 'opening_number'
                ],
                'course_name' =>[
                    'name' => '课程名称',
                    'obj_type' => 'course_name'
                ]
            ];
            //给课程保存的时候添加一个地区属性
            $mechanic=Mechanic::find()->where(['id'=>$model->mechanic_id])->asArray()->one();
            foreach($mechanic as $k=>$v){
                if($k=='region'){
                    $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$mechanic['id'],'name'=>'地域','value'=>$mechanic['region'],'obj_type'=>'region']);
                    $attributes->save(false);
                }
            }
            $arrange=$arrangement->toArray([],['class_day', 'start_time', 'end_time', 'course_name', 'teacher_name','room_number','room_name','teacher_form']);
            foreach($arrange as $k=>$v){
                if(in_array($k,['course_id','teacher_id','classroom_id','class_day', 'start_time', 'end_time','class_length','class_count','max_number','opening_number','is_booking','teacher_form'])){
                    if($k=='course_id'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$v,'name'=>'课程','value'=>$arrange['course_name'],'obj_type'=>'course']);
                        $attributes->save(false);
                    }elseif($k=='teacher_id'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$v,'name'=>'老师','value'=>$arrange['teacher_name'],'obj_type'=>'teacher']);
                        $attributes->save(false);
                    }elseif($k=='classroom_id'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$v,'name'=>'教室编号','value'=>$arrange['room_number'],'obj_type'=>'classroom_number']);
                        $attributes->save(false);
                        $attributes_1=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$v,'name'=>'教室名称','value'=>$arrange['room_name'],'obj_type'=>'classroom_name']);
                        $attributes_1->save(false);
                    }elseif($k=='class_day'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['classroom_attr_id'],'name'=>'上课星期','value'=>$arrange['class_day'],'obj_type'=>'class_day']);
                        $attributes->save(false);
                    }elseif($k=='start_time'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['classroom_attr_id'],'name'=>'上课时间','value'=>$arrange['start_time'],'obj_type'=>'start_time']);
                        $attributes->save(false);
                    }elseif($k=='end_time'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['classroom_attr_id'],'name'=>'下课时间','value'=>$arrange['end_time'],'obj_type'=>'end_time']);
                        $attributes->save(false);
                    }elseif($k=='is_booking'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['id'],'name'=>'是否可预约','value'=>$v,'obj_type'=>'is_booking']);
                        $attributes->save(false);
                        if($v == 1){
                            $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['id'],'name'=>'预约课次','value'=>$arrange['booking_count'],'obj_type'=>'booking_count']);
                            $attributes->save(false);
                            $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['id'],'name'=>'预约价格','value'=>$arrange['booking_price'],'obj_type'=>'booking_price']);
                            $attributes->save(false);
                        }
                    }elseif($k=='teacher_form'){
                        $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$v,'name'=>'授课方式','value'=>$arrange['teacher_form'],'obj_type'=>'teacher_form']);
                        $attributes->save(false);
                    }else{
                            $attributes=new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$arrange['id'],'name'=>$fleds[$k]['name'],'value'=>$v,'obj_type'=>$fleds[$k]['obj_type']]);
                            $attributes->save(false);
                        }
                    }
                }
            }
            return $this->controller->redirectMessage('添加成功',Fun::url(['goodscourse/index','type_id'=>1]));
        }catch (Exception $e) {
            $transaction->rollBack();
            /*\Yii::error('------------------save goods error:--------------');
            \Yii::error($e);*/
            return $this->controller->redirectMessage('添加失败',Fun::url(['goodscourse/index','type_id'=>1]));
        }
    }

    //普通消费商品保存
    public function ProductSave($model, $post){
        $transaction = \Yii::$app->db->beginTransaction();
       // var_dump($transaction);die;
        try{
            $model->sn = 'product'.time();
            $model->type_id = $this->type;
            $model->site_id = Fun::getSiteId();
            $model->goods_type = 'normal';
            $model->admin_id=\Yii::$app->user->id;
            if(isset($post['Goods']['imageList']) && !empty($post['Goods']['imageList'])){
                $imagelist = $post['Goods']['imageList'];
                $imagelist_arr = [];
                if(!empty($imagelist)){
                    $imagelist_arr = explode('#|#',$imagelist);
                }
                if(!empty($post['Goods']['defaulturl'])&&in_array($post['Goods']['defaulturl'],$imagelist_arr)){
                    $model->picture = $post['Goods']['defaulturl'];
                }else{
                    if(count($imagelist_arr)>0){
                        $model->picture = $imagelist_arr[0];//上传的列表第一个作为展示的默认图
                    }else{
                        $model->picture = '';
                    }
                }
            }else{
                $model->picture = '';
            }

            if($model->is_shelve==1){
                $model->up_at=time();
            }
            if($model->save(false)){//保存至goods表成功之后，开始保存扩展属性至表goods_attr
                $attribute = isset($post['attribute'])?$post['attribute']:null;
                if(!empty($attribute)){
                    if(!empty($post['attr_value'])){
                        foreach($post['attr_value'] as $k=>$v){
                            if(!empty($v)){//非空的扩展属性值进行保存
                                $attributes = new GoodsAttr(['goods_id'=>$model->id,'attribute_id'=>$k,'name'=>$attribute[$k],'value'=>trim($v),'obj_type'=>'attribute']);
                                $attributes->save(false);
                            }
                        }
                    }
                }

            }
            $transaction->commit();
            return $this->controller->redirectMessage('添加成功',Fun::url(['goodsproduct/index','type_id'=>$this->type]));
        }catch (Exception $e){
            $transaction->rollBack();
            /*\Yii::error('------------------save product error:--------------');
            \Yii::error($e);*/
            return $this->controller->redirectMessage('添加失败',Fun::url(['goodsproduct/index','type_id'=>$this->type]));
        }
    }

}